package GUI; //done

import java.awt.Color;
import java.awt.HeadlessException;
import java.awt.SystemColor;

import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

import Client.ConnectionToServer;
import Entities.Category;

/**
 * This Class controls Category Update Window.
 * @author ameer
 * @author waleed
 * @author bshara
 * @author kamil
 */
public class CategoryUpdateWindow extends TypeManagementWindow {
	/** The serial Version UID. */
	private static final long serialVersionUID = 1L;
	
	/** The add flag Variable. */
	private boolean addflag;
	
	/** The update flag Variable. */
	private boolean updateflag;
	
	/** The remove flag Variable. */
	private boolean removeflag;
	
	/** The Category. */
	private Category category = null; 
	
	/** The Background Label. */
	private JLabel BackgroundLabel;
	
	/**
	 * Default constructor
	 */
	public CategoryUpdateWindow(){
		super();
		getUpdateButton().setLocation(214, 170);
		getRemoveButton().setLocation(314, 170);
		getSectionsIDLabel().setText("All Categories :");
		getSaveButton().setLocation(116, 170);
		getCancelButton().setLocation(15, 170);
		setBackground(SystemColor.activeCaption);
		initialize(); 
	}
	
	/**
	 * This function initializes CategoryUpdateWindow
	 */
	private void initialize() {
		category = new Category(0,"");		
		addflag = false;
		updateflag = false;
		removeflag = false;
		updateCategoriesIDComboBox();
		getIdLabel().setText("Category ID");
		getNameLabel().setText("Category name");
		getTypesIDLabel().setText("All types in this Category");
		getProductsIDLabel().setText("All Product in this Type");
		getAddbuttonLabel().setText("Selected Category info:");
		getNameTextField().setEditable(false);
		getIdTextField().setEditable(false);
		addSaveButton();
		addUpdateButton();
		addremoveButton();
		addTypesIDComboBox();
		addCategoryIDComboBox();	
		
		BackgroundLabel = new JLabel("");
		BackgroundLabel.setIcon(new ImageIcon(AddCustomerInterestWindow.class.getResource("/Pictures/bg.png")));
		BackgroundLabel.setBounds(-13, -471, 628, 721);
		this.add(BackgroundLabel);		
		
	}
	
	/**
	 * This function update form comboBoxes from DB
	 */
	public void updateForm(){
		updateCategoriesIDComboBox();
	}
	
	/**
	 * This function initializes categoryIDComboBox ActionListener
	 */
	private void addCategoryIDComboBox(){
		getCategoryIDComboBox().addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent e) {	
				int categoryID = 0;
				String str = (String)getCategoryIDComboBox().getSelectedItem();
				if (str.equals(":"))
					return;
				try{
					categoryID = Integer.parseInt(str.substring(0, str.indexOf(":")));
				}
				catch( NumberFormatException exc){
					return;
				}
				if (categoryID > 0){
					getIdTextField().setText(String.valueOf(categoryID));
					getNameTextField().setText(str.substring(str.indexOf(":")+1, str.length()));
				}
				else{
					getIdTextField().setText("");
					getNameTextField().setText("");
					return;
				}
				category.SetCategoryID(categoryID);
				String[] typelist = null;
				try{
					int i=0,itemcount = getTypesIDComboBox().getItemCount();
					if (itemcount > 0) {
						getTypesIDComboBox().addItem(":");
						getTypesIDComboBox().setSelectedItem(":");				
					}
					for (i=0; i < itemcount ; i++ ){				
						getTypesIDComboBox().removeItemAt(0);						
					}			
					typelist = category.GetAllCategoryTypes();
					if (typelist != null){
						int len = typelist.length;
						for(i=0; i < len; i++){
							getTypesIDComboBox().addItem(typelist[i]);							
						}						
					}	
				}
				catch(Exception except){
					JOptionPane.showMessageDialog(null, "SYSTEM ERROR!!!","",JOptionPane.ERROR_MESSAGE);
				}				
			}
		});	
	}
	
	/**
	 * This function initializes typesIDComboBox
	 */
	private void addTypesIDComboBox(){
		getTypesIDComboBox().addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent e) {			
				String str = (String)getTypesIDComboBox().getSelectedItem();
				if (str.equals(":")){
					getProductsIDTextArea().setText("");
					return;
				}
				String typeID = str.substring(0, str.indexOf(":"));
				String[] productslist = null;
				try{
					ConnectionToServer connectiontoserver = new ConnectionToServer();		
					productslist = (String[]) connectiontoserver.loadTypeProduct(Integer.parseInt(typeID));
					if (productslist == null){
						getProductsIDTextArea().setText("");
					}							
					else{
						String tmpstr = "";
						int len = productslist.length;
						for(int i=0; i < len; i++){
							tmpstr = tmpstr+(productslist[i]+"\n");
						}
						getProductsIDTextArea().setText(tmpstr);
					}
				}
				catch(Exception except){
					JOptionPane.showMessageDialog(null, "SYSTEM ERROR!!!","",JOptionPane.ERROR_MESSAGE);
				}
			}
		});		
	}
	
	/**
	 * This function initializes SaveButton ActionListener
	 */
	private void addSaveButton(){
		getSaveButton().addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent e) {			
				if (addflag){
					saveCategory();										
				}
				else{
					getSaveButton().setText("OK");
					getAddbuttonLabel().setText("PLZ enter category ID and Name:");
					getNameTextField().setEditable(true);
					getIdTextField().setEditable(true);
					getUpdateButton().setEnabled(false);
					getRemoveButton().setEnabled(false);
					getIdTextField().setForeground(Color.red);
					getNameTextField().setForeground(Color.red);
					getAddbuttonLabel().setForeground(Color.red);
					addflag = true;
				}
			}
		});		
	}
	
	/**
	 * This function initializes updateButton ActionListener
	 */
	private void addUpdateButton(){
		getUpdateButton().addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent e) {			
				if (updateflag){
					updateSection();	
				}
				else{
					getUpdateButton().setText("OK");
					getAddbuttonLabel().setText("PLZ enter new category name:");
					getNameTextField().setEditable(true);
					getRemoveButton().setEnabled(false);
					getSaveButton().setEnabled(false);
					getIdTextField().setForeground(Color.red);
					getNameTextField().setForeground(Color.red);
					getAddbuttonLabel().setForeground(Color.red);
					updateflag = true;
				}
			}
		});		
	}
	
	/**
	 * This function update selected category
	 */
	private void updateSection(){
		int categoryID = 0;
		try{
			categoryID = Integer.parseInt(getIdTextField().getText());
		}
		catch(NumberFormatException exception){
			return;
		}					
		String sectionName = getNameTextField().getText();
		if (categoryID > 0 && !sectionName.equals("")){
			category.SetCategoryID(categoryID);
			category.SetCategoryName(sectionName);
			try {
				if (category.updateCategory()){
					String oldname = (String)getCategoryIDComboBox().getSelectedItem();
					oldname = oldname.substring(oldname.indexOf(":")+1, oldname.length());
					getCategoryIDComboBox().removeItem(categoryID+":"+oldname);
					getCategoryIDComboBox().addItem(categoryID+":"+sectionName);
					JOptionPane.showMessageDialog(null, "Category successfuly update");
					restore();			
				}
				else
					JOptionPane.showMessageDialog(null, "Category not updated!","",JOptionPane.WARNING_MESSAGE);
			} 
			catch (Exception e1) {
				JOptionPane.showMessageDialog(null, "FATAL ERROR!!!","",JOptionPane.ERROR_MESSAGE);							
			}						
		}
		else
			JOptionPane.showMessageDialog(null, "PLZ enter category name!","",JOptionPane.WARNING_MESSAGE);
	}
	
	
	/**
	 * This function add entered category to data base
	 */
	private void saveCategory(){
		int categoryID = 0;
		try{
			categoryID = Integer.parseInt(getIdTextField().getText());
		}
		catch(NumberFormatException exception){
			JOptionPane.showMessageDialog(null, "Ilegal ID","",JOptionPane.WARNING_MESSAGE);
			return;
		}					
		String sectionName = getNameTextField().getText();
		if (categoryID > 0 && !sectionName.equals("")){
			category.SetCategoryID(categoryID);
			category.SetCategoryName(sectionName);
			try{
				if (category.addCategory()){
					JOptionPane.showMessageDialog(null, "Category saved successfuly");
					getCategoryIDComboBox().addItem(categoryID+":"+sectionName);
					restore();
				}
				else
					JOptionPane.showMessageDialog(null, "Category ID already exists!","",JOptionPane.WARNING_MESSAGE);
			} 
			catch (Exception e1) {
				JOptionPane.showMessageDialog(null, "FATAL ERROR!!!","",JOptionPane.ERROR_MESSAGE);							
			}						
		}
		else
			JOptionPane.showMessageDialog(null, "Ilegal input!","",JOptionPane.WARNING_MESSAGE);		
	}
	
	/**
	 * This function initializes removeButton ActionListener
	 */
	private void addremoveButton(){
		getRemoveButton().addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent e) {	
				if (removeflag){
					removeCategory();	
					restore();
				}
				else{
					getRemoveButton().setText("OK");
					getAddbuttonLabel().setText("Remove this category:");
					getUpdateButton().setEnabled(false);
					getSaveButton().setEnabled(false);
					getIdTextField().setForeground(Color.red);
					getNameTextField().setForeground(Color.red);
					getAddbuttonLabel().setForeground(Color.red);
					removeflag = true;
				}
			}
		});		
	}
	
	/**
	 * This function remove selected category from data base
	 */
	private void removeCategory(){
		int categoryID = 0;
		try{
			categoryID = Integer.parseInt(getIdTextField().getText());
		}
		catch(NumberFormatException exception){
			return;
		}		
		category.SetCategoryID(categoryID);
		try{
			if (category.removeCategory()){
				getCategoryIDComboBox().removeItem(categoryID+":"+getNameTextField().getText());
				JOptionPane.showMessageDialog(null, "Category successfuly remove");				
			}
			else
				JOptionPane.showMessageDialog(null, "Category not remove!!!","",JOptionPane.WARNING_MESSAGE);			
		} 
		catch (HeadlessException e1) {
			JOptionPane.showMessageDialog(null, "System ERROR!!!","",JOptionPane.ERROR_MESSAGE);							
			
		} 
		catch (Exception e1) {
			JOptionPane.showMessageDialog(null, "FATAL ERROR!!!","",JOptionPane.ERROR_MESSAGE);							
		}		
	}
	
	/**
	 * This function restore the form button  
	 */
	public void restore(){
		getSaveButton().setText("Add new");	
		getUpdateButton().setText("UPDATE");	
		getRemoveButton().setText("Remove");
		getAddbuttonLabel().setText("Selected category info:");	
		addflag = false;
		updateflag = false;
		removeflag = false;
		getIdTextField().setForeground(Color.black);
		getNameTextField().setForeground(Color.black);
		getAddbuttonLabel().setForeground(Color.black);
		getNameTextField().setEditable(false);
		getIdTextField().setEditable(false);
		getIdTextField().setText("");
		getNameTextField().setText("");
		getUpdateButton().setEnabled(true);
		getRemoveButton().setEnabled(true);
		getSaveButton().setEnabled(true);
	}
}
